package com.itic.appbase.applications.login.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.login.service.LoginService;
import com.itic.appbase.applications.sys.resource.persistence.model.Resource;
import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.MD5Helper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.tree.TreeHelper;
import com.itic.appbase.framework.utils.tree.TreeNode;

/**
 * 
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: xujing
 * @date: 2015年5月15日 下午3:15:16
 * @version: V1.0
 */
@Controller
@RequestMapping("/")
public class IndexController
        extends BaseController {
    @Autowired
    private LoginService indexService;

    /**
     * 跳转到登录页面
     * 
     * @return
     */
    @RequestMapping(value = "/index")
    public String execute(HttpServletRequest request) {
        if (StringHelper.isNotEmpty(this.findUserId(request))) {
            return "main";
        }
        return "redirect:" + "login";
    }

    /**
     * 跳转到首页面
     * 
     * @return
     */
    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }
    
    /**
     * 跳转到修改密码
     * 
     * @return
     */
    @RequestMapping(value = "/pwdChange", method = RequestMethod.GET)
    public String password(HttpServletRequest request, Model model) {
        model.addAttribute("username", this.findUserSession(request).getUsername());
        return "/modifyPwd";
    }

    /**
     * 修改密码
     * 
     * @param request
     * @param response
     * @param model
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws Exception
     */
    @RequestMapping(value = "/pwdChange", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> password(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.UNKOWN_ERROR.getCode();

        String oldPassword = this.getCleanParams(request, "curPwd");
        String newPassword = this.getCleanParams(request, "newPwd");
        User user = this.findUserSession(request);
        if (null != user && StringHelper.isNotBlank(oldPassword)) {
            String pwdDb = user.getPassword();
            // 密码处理
            oldPassword = MD5Helper.md5DoubleSalt(oldPassword, user.getUsername());
            // 密码匹配
            if (oldPassword.equals(pwdDb)) {
                // 修改密码
                User sUser = indexService.get(user);
                sUser.setPassword(MD5Helper.md5DoubleSalt(newPassword, user.getUsername()));
                String upCode = indexService.editPassword(sUser);
                if ("success".equals(upCode)) {
                    // 刷新用户session
                    this.setUserSession(request, sUser);
                    result = ResponseCode.SUCCESS.getCode();
                } else {
                    result = ResponseCode.UNKOWN_ERROR.getCode();
                }
            } else {
                result = "invalid_pwd";
            }
        } else {
            result = "invalid_pwd";
        }
        resultMap.put("result", ResponseCode.SUCCESS.getCode());
        resultMap.put("data", result);
        return resultMap;
    }

    /**
     * 导航栏-获取用户资源
     * 
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getUserResource")
    @ResponseBody
    public Map<String, Object> getUserResource(HttpServletRequest request)
            throws IOException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        User user = this.findUserSession(request);
        List<Resource> resourceList = indexService.getResourceByUserId(user.getId());
        List<? extends TreeNode> treeList = new ArrayList<TreeNode>();
        if (null != resourceList && !resourceList.isEmpty()) {
            List<TreeNode> resourceTreeList = new ArrayList<TreeNode>();
            for (Resource resource : resourceList) {
                Map<String, Object> attribute = new HashMap<String, Object>();
                TreeNode node = new TreeNode();
                node.setId(resource.getId());
                node.setParentId(resource.getpId());
                node.setText(resource.getName());
                attribute.put("url", resource.getUrl());
                attribute.put("mark", resource.getMark());
                attribute.put("permit", resource.getPermit());
                attribute.put("sName", resource.getsName());
                node.setAttributes(attribute);
                resourceTreeList.add(node);
            }
            treeList = TreeHelper.getTree(resourceTreeList);
        }
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, treeList);
        return resultMap;
    }
}